package cn.com.oceansoft.nos.common.spring;

import cn.com.oceansoft.business.sys.entity.DictItem;
import cn.com.oceansoft.business.sys.persistence.ISysDictMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;

/**
 * Created by chenw on 2014/8/12.
 */
public class SystemInitListener implements ServletContextListener {

    Logger logger = LoggerFactory.getLogger(getClass());

    @Override
    public void contextInitialized(ServletContextEvent servletContextEvent) {
        ServletContext servletContext = servletContextEvent.getServletContext();

       /* ISysDictMapper sysDictMapper = SpringContextHolder.getBean("ISysDictMapper");
        List<DictItem> list = sysDictMapper.findAllDictByZtree();
        HashMap<String, LinkedHashMap<String, String>> dictionary = processDictItems(list);
        //FIXME:此处修改为将缓存数据初始化Redis中
        for (String key : dictionary.keySet()) {
            servletContext.setAttribute(key, dictionary.get(key));
            logger.debug("加载字典配置key={},value={}", key, dictionary.get(key).toString());
        }*/
    }


    @Override
    public void contextDestroyed(ServletContextEvent servletContextEvent) {
        ServletContext servletContext = servletContextEvent.getServletContext();
        logger.info("正在清除系统缓存...");
        servletContext.setAttribute("superAdminDB", null);
        servletContext.setAttribute("ueditorConfig", null);
        logger.info("系统缓存清除完毕！");
    }

    private HashMap<String, LinkedHashMap<String, String>> processDictItems(List<DictItem> list) {
        //
        HashMap<Integer, String> id2Key = new HashMap<>();
        HashMap<String, LinkedHashMap<String, String>> result = new HashMap<>();
        //
        for (DictItem item : list) {
            int children = item.getChildren();
            if (0 < children) {//
                id2Key.put(item.getId(), item.getKey());
                result.put(item.getKey(), new LinkedHashMap<>());
            }
        }

        for (DictItem item : list) {
            int parentId = item.getParentId();
            if (id2Key.containsKey(parentId)) {
                LinkedHashMap combox = result.get(id2Key.get(parentId));
                combox.put(item.getKey(), item.getVal());
            }
        }
        return result;
    }
}
